const Koa = require('koa'),
    router = require('koa-router')(),
    render = require('koa-art-template')
    path = require('path'),
    static = require('koa-static'),
    admin = require('./routers/admin'),
        koaBody = require('koa-body'),
    session = require('koa-session');

const app = new Koa();

// 配置art-template   所有模板文件放入view下
render(app, {
    root: path.join(__dirname, 'view'),
    extname: '.html',
    debug: process.env.NODE_ENV !== 'production'
  });

// 配置静态资源
app.use(static('static'));

// 配置koa-body接受前端的请求体数据
app.use(koaBody({
    multipart:true
}));

// 配置session    cooklie中的key值
app.keys = ['some secret hurr'];

const CONFIG = {
  key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
    /** Warning: If a session cookie is stolen, this cookie will never expire */
    // 默认有效期1天
  maxAge: 86400000,

  autoCommit: true, /** (boolean) automatically commit headers (default true) */
//     能不能写
  overwrite: true, /** (boolean) can overwrite or not (default true) */
//   cookie是否只有服务端可以访问
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
//   签名
  signed: true, /** (boolean) signed or not (default true) */
//   
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
//是否可以覆盖，到期前进行访问，更新到期时间
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
//   使用https进行访问 ，需要改成http改成false
  secure: false, /** (boolean) secure cookie*/
  sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};

app.use(session(CONFIG, app));
// or if you prefer all default config, just use => app.use(session(app));



// 路由
//404页面不存在（中间件）

app.use(async (ctx,next)=>{
    await next();
    if(ctx.status===404){
        ctx.body="抱歉，页面不存在";
    }
})

//根
router.get('/',ctx=>{
// 模板文件名
    ctx.render("home");
    // ctx.body="<div><h2>首页</h2></div>"
})

// 设置session
router.get('/setsession', ctx => {
    ctx.body = 'session 设置成功'
    // 存值  将key保存在cookies中  koa-sess是键值
    ctx.session.title = 'mytitle';
    ctx.session.name = 'jack';
    ctx.session.status = 1;

})
// 获取session
router.get('/getsession', ctx => {
    
    let title = ctx.session.title;
    ctx.body = title;
    console.log(title);

})
// 销毁session
router.get('/destroysession', ctx => {
    ctx.body="session销毁成功"
    ctx.session.title = '';//false null ''
    // 销毁所有
    ctx.session = null;
})

// 配置路由（建议写在开启服务器的前面）
app
    .use(router.routes())
    .use(router.allowedMethods());

// 开启服务器监听
app.listen(2022,()=>{
    console.log("#localhost:2022");
})